# -*- coding: utf-8 -*-
from typing import List, Dict, Set, Tuple
import random


class IdFactory:
    cache: Dict[str, Dict[str, int]] = {}

    @classmethod
    def generate_int_id(cls, key:str=None, group: str="default", range: Tuple[int, int]=(0, 10000)):
        if not cls.cache.get(group, None):
            cls.cache[group] = dict()
        def generate_id(key=key):
            id = random.randint(range[0], range[1])
            if id not in cls.cache[group].values():
                key = key if key is not None and len(key) > 0 else str(id)
                cls.cache[group][key] = id
                return id
            else:
                generate_id()
        return generate_id()

    @classmethod
    def get_key_by_id(cls, id:int, group: str="default") -> str:
        """
        通过id获取其对应的key
        :param id:
        :param group:
        :return:
        """
        group = group if group is not None and len(group) > 0 else "default"
        id_dict = cls.cache.get(group)
        if id_dict is not None and len(id_dict) > 0:
            if id in id_dict.values():
                for k, v in id_dict.items():
                    if v == id:
                        return k
        return None

    @classmethod
    def get_id_by_key(cls, key:str, group: str="default") -> str:
        """
        通过key获取其对应的id
        :param id:
        :param group:
        :return:
        """
        if key is None or len(key) == 0:
            return None
        group = group if group is not None and len(group) > 0 else "default"
        id_dict = cls.cache.get(group)
        if id_dict is not None and len(id_dict) > 0:
            if key in id_dict.keys():
                for k, v in id_dict.items():
                    if key == k:
                        return v
        return None